<?php

namespace App\Console\Commands\WaiMai;

use App\Console\Commands\Traits\ExcelCommandTrait;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;
use Kuafu\File\FileUtil;

class BusinessAnalysisCommand extends Command
{
    use ExcelCommandTrait;

    protected $signature   = 'waimai:analysis';
    protected $description = '外卖评估';

    private array $data = [];

    const RDK_THIRD_SHOP_GEO = 'BusinessAnalysisCommandGeos';

    const RDK_THIRD_SHOP_HASH = 'BusinessAnalysisCommandAna';

    const CACHE_KF_SHOPS = 'BusinessAnalysisCommand:kfShops';

    public function handle()
    {
        ini_set('memory_limit', '10240M');

//        $this->updateKfShop();


        // 把三方数据写进Cache中
//        $this->prepareThirdShopCsv();

        // kf门店数据
//        $this->getKfShops();
//die;
        foreach ($this->kfShops as $k => $shop) {
            $shopCode    = $shop[0];
            $shopName    = $shop[1];
            $shopLat     = $shop[2];
            $shopLng     = $shop[3];
            $mtOrderNum  = $shop[4];
            $elmOrderNum = $shop[5];

//            if ($shopCode != 11111) {
//                continue;
//            }

            if (!$shopLng || !$shopLat) {
                continue;
            }

            $elm = [
                'total'      => [],
                'total100'   => [],
                'kf100'      => [],
                'fried'      => [],
                'fried100'   => [],
                'friedkf100' => [],
            ];

            $mt = [
                'total'      => [],
                'total100'   => [],
                'kf100'      => [],
                'fried'      => [],
                'fried100'   => [],
                'friedkf100' => [],
            ];

            $nearbyShops = Redis::connection('default')
                                ->client()
                                ->geoRadius(self::RDK_THIRD_SHOP_GEO, $shopLng, $shopLat, 3, 'km',
                                    ['WITHDIST', 'ASC', 'WITHCOORD', 'COUNT', 5000]);

//            $this->info($shopName . '-' . count($nearbyShops));

            foreach ($nearbyShops as $nearbyShop) {
                $hash      = $nearbyShop[0];
                $thirdInfo = Redis::connection('default')->client()->hGet(self::RDK_THIRD_SHOP_HASH, $hash);
                $thirdInfo = json_decode($thirdInfo, true);

                $thirdOrderNum     = $thirdInfo['orderNum'];
                $thirdCategoryName = $thirdInfo['categoryName'];
                $sourceType        = $thirdInfo['sourceType'];

                if ($sourceType == 4) {
                    $this->buildWmArr($elm, $thirdCategoryName, $thirdOrderNum);
                } elseif ($sourceType == 3) {
                    $this->buildWmArr($mt, $thirdCategoryName, $thirdOrderNum);
                }
            }

            foreach ($elm as &$v) {
                $v = $this->calcNum($v);
            }

            foreach ($mt as &$v) {
                $v = $this->calcNum($v);
            }
            $this->data[] = [
                $shopCode,
                $shopName,
                $elmOrderNum,
                $mtOrderNum,
                $elm['total'],
                $mt['total'],
                $elm['total100'],
                $mt['total100'],
                $elm['kf100'],
                $mt['kf100'],
                $elm['fried'],
                $mt['fried'],
                $elm['fried100'],
                $mt['fried100'],
                $elm['friedkf100'],
                $mt['friedkf100'],
            ];

            $this->info($k);
        }

        $this->export([
            '夸父门店编号',
            '夸父门店名称',
            '现有外卖销量（饿了么）',
            '现有外卖销量（美团）',
            "全品类订单月销量预估（饿了么）",
            "全品类订单月销量预估（美团）",
            "超100单全品类订单月销量预估（饿了么）",
            "超100单全品类订单月销量预估（美团）",
            "包括夸父门店超100单全品类订单月销量预估（饿了么）",
            "包括夸父门店超100单全品类订单月销量预估（美团）",
            "炸鸡炸串类订单月销量预估（饿了么）",
            "炸鸡炸串类订单月销量预估（美团）",
            "超100单炸鸡炸串类订单月销量预估（饿了么）",
            "超100单炸鸡炸串类订单月销量预估（美团）",
            "包括夸父门店超100单炸鸡炸串类订单月销量预估（饿了么）",
            "包括夸父门店超100单炸鸡炸串类订单月销量预估（美团）"
        ], $this->data);
    }


    public function export(array $headers, array $data)
    {
        // UTF8的BOM头
        $path = sys_get_temp_dir() . '/' . Str::random() . '.csv';
        $fd   = fopen($path, 'w+');
        fwrite($fd, "\xEF\xBB\xBF");

        // 表头
        if ($headers) {
            fputcsv($fd, $headers);
        }

        collect($data)->each(function ($item) use (&$fd) {
            fputcsv($fd, $item);
        });


        if (is_resource($fd)) {
            fclose($fd);
        }

        dump($path);

        $detailUrl = FileUtil::uploadFile($path, 'csv',
            "tmp/" . date('Ymd') . '/' . Str::uuid() . '.csv')['url'];
        dump($detailUrl);
    }


    private function prepareThirdShopExcel()
    {
        $this->setInputExcel(false);

        // 把所有数据写进Cache中
        $url = 'https://file.51kuafu.com/0a/bc/faec28ce1bc9794c830c648b0730c0bb5562dec9f3441ce5b36dcd53a6fe.xlsx';
        $this->setExcelCommandData(['sourceType' => 3]);
        $this->excelImport(ImportData::class, $url);

        $url = 'https://file.51kuafu.com/83/cd/02d82e1daae8855ac2abea9e12b1824c3739eb2dbe2738a84fe3d4f28941.xlsx';
        $this->setExcelCommandData(['sourceType' => 4]);
        $this->excelImport(ImportData::class, $url);
    }



    private array $kfShops    = [];
    private array $thirdShops = [];

    /**
     * 获取夸父门店的信息 - 经纬度、美团订单数量、饿了么订单数量
     * @return void
     */
    private function getKfShops()
    {
        Cache::forget(self::CACHE_KF_SHOPS);

        $this->kfShops = Cache::remember(self::CACHE_KF_SHOPS, 3600 * 6, function () {

            $this->updateKfShop();

            return $this->kfShops;
        });
    }


//    /**
//     * 批量增加geo信息
//     * @param array $data
//     * @return void
//     */
//    public function addGeo()
//    {
//        WaiMaiAnalysisModel::query()->select('id', 'lat', 'lng')->chunkById(10000, function ($models) {
//            Redis::pipeline();
//
//            $models->map(function ($model) {
//                Redis::geoAdd(WaiMaiAnalysisService::RDK_WAI_MAI_ANALYSIS_GEO, $model->lng, $model->lat, $model->id);
//            });
//
//            Redis::exec();
//
//            if ($models->first()) {
//                $this->info($models->first()->id);
//            }
//        });
//    }



}

class ImportData
{
    private int $sourceType;

    public function collection(Collection $collection, ?Command $command)
    {
        $collection->first()->map(function ($item, $row) {
            $row = $row + 1;
            if ($row == 1) {
                return null;
            }

            if (!$item[0] || !$item[1] || !$item[2]) {
                return null;
            }

            foreach ($item as &$v) {
                $v = (string)$v;
                $v = trim($v);
            }

            BusinessAnalysisCommand::putDataInfoHash(
                $this->sourceType,
                $row,
                $item[0],
                (string)$item[3],
                (int)$item[4],
                trim($item[2]),
                trim($item[1]),
            );

            dump($row);
        });

    }

    public function setCommandData(array $data): self
    {
        $this->sourceType = $data['sourceType'];

        return $this;
    }


}
